<template>
  <!--查询区-->
  <div class="search">
    <el-form inline :model="memberSearchModel" ref="memberSearchReset">
      <el-form-item  label="姓名:" prop="name">
        <el-input style="width: 150px;" placeholder="请输入姓名" v-model="memberSearchModel.name"/>
      </el-form-item>
      <el-form-item label="电话:" prop="phone" >
        <el-input style="width: 150px" placeholder="请输入电话号码" v-model="memberSearchModel.phone"/>
      </el-form-item>
      <el-form-item label="注册日期:" prop="regisdateRange" >
              <el-date-picker
                  v-model="memberSearchModel.regisdateRange"
                  type="daterange"
                  range-separator="~"
                  start-placeholder="日期从"
                  end-placeholder="日期到"
                  value-format="YYYY-MM-DD"
              />
      </el-form-item>
      <el-form-item>
        <el-button type="success" @click="search()">查询</el-button>
        <el-button type="info" @click="reset">重置</el-button>
        <el-button type="warning"  @click="add">添加</el-button>
      </el-form-item>
    </el-form>
  </div>

  <!--表格区
    遇到的问题1：prop要与后端的响应发回的名相对应，否则即使响应到数据也无法显示到前端
  -->
  <div class="grid">
    <el-table :data="members" stripe border ref="tbf" @row-click="YourPet" class="data-grid" >
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column prop="id" label="ID" width="85"/>
      <el-table-column label="头像" :width="90" fixed>
        <template #default="scope">
          <div class="row-avatar" :style="'background-image:url('+(baseUrl+scope.row.avatar)+')'"></div>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="姓名" width="150"/>
      <el-table-column prop="phone" label="电话" width="150"/>
      <el-table-column prop="isMember" label="是否是会员" width="150"/>
      <el-table-column prop="regisdate" label="注册日期" width="150"/>
      <el-table-column prop="integral" label="积分" width="60"/>
      <el-table-column prop="wechat" label="微信" width="150"/>
      <el-table-column label="操作" width="160" align="center">
        <template #default="scope">
          <el-button type="primary" @click.stop="edit(scope.row)">编辑</el-button>
          <el-button type="danger" @click.stop="withPets(scope.row)">删除</el-button>
        </template>
      </el-table-column>
      <el-table-column prop="description" label="备注信息"/>
    </el-table>
  </div>
  <!--分页区-->
  <div class="pagination">
        <el-pagination
            v-model:current-page="memberPi.pageNo"
            v-model:page-size="memberPi.pageSize"
            :page-sizes="[10, 20, 30, 50,100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="memberPi.total"
            class="member-pi"
            background
            @change="memberPiChange"
        />
  </div>
  <!--弹出表单区-->
  <el-dialog v-model="memberDlgShow" :title="memberDlgTitle" :width="600" @close="clearAll"  :close-on-click-modal="false" draggable align-center>
    <el-form :model="memberModel" label-width="100" :rules="rules" label-position="left" ref="memberDlgForm">
      <el-row>
        <el-col span="16">
          <el-form-item label="姓名:" prop="name">
            <el-input v-model="memberModel.name" placeholder="请输入姓名"/>
          </el-form-item>

          <el-form-item label="电话:" prop="phone">
            <el-input v-model="memberModel.phone" placeholder="请输入电话"/>
          </el-form-item>

          <el-form-item label="注册日期:" prop="regisdate">
            <el-date-picker v-model="memberModel.regisdate" placeholder="请输入注册日期" value-format="YYYY-MM-DD"></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col span="8">
          <el-upload
              class="avatar"
              :show-file-list="false"
              :http-request="customUpload"
              prop="avatar"
          >
          <div class="img" v-if="memberModel.avatar" :style="'background-image:url('+(baseUrl+memberModel.avatar)+')'"></div>
          <el-icon v-else class="avatar-uploader-icon">
            <Plus/>
          </el-icon>
          </el-upload>
        </el-col>
      </el-row>
      <el-form-item label="是否是会员:" prop="isMember">
        <el-radio-group v-model="memberModel.isMember">
          <el-radio label="是" value="是"/>
          <el-radio label="否" value="否"/>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="微信:" prop="wechat">
        <el-input v-model="memberModel.wechat" placeholder="请输入微信"/>
      </el-form-item>

      <el-form-item label="积分：" prop="integral">
        <el-input v-model="memberModel.integral" placeholder="请输入您的积分"/>
      </el-form-item>

      <el-form-item label="备注:" prop="description">
        <el-input v-model="memberModel.description" placeholder="请输入备注"/>
      </el-form-item>
    </el-form>

    <template #footer>
      <div>
        <el-button type="primary" @click="doSubmit" >确定</el-button>
        <el-button type="primary" @click="memberDlgShow=false">取消</el-button>
      </div>
    </template>
  </el-dialog>

  <el-dialog v-model="memberDlgShow2" :title="memberDlgTitle2" :width="600" draggable align-center :close-on-click-modal="false">
    <el-table :data="pets" stripe border ref="petRbf" >
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column prop="petsId" label="宠物Id" width="85"/>
      <el-table-column prop="petName" label="名字" width="90"/>
      <el-table-column prop="petKind" label="物种" width="90"/>
      <el-table-column prop="petSex" label="性别" width="60">
      <template #default="scope">
        <el-tag v-if="scope.row.petSex==='公'" type="primary" effect="dark">{{scope.row.petSex}}</el-tag>
        <el-tag v-else type="danger" effect="dark">{{scope.row.petSex}}</el-tag>
      </template>
    </el-table-column>
      <el-table-column prop="petAge" label="年龄" width="60"/>
      <el-table-column prop="petVariety" label="种类"/>
    </el-table>
  </el-dialog>
</template>

<style>
  .el-upload{
    width: 100%;
  }
</style>


<style scoped>
.avatar{
  width: 140px;
  height:140px;
  border: 1px dashed #ccc;
  border-radius: 4px;
  margin-left: 8px;
  display: flex;
}

.avatar .img{
  width: 140px;
  height: 140px;
  background-repeat: no-repeat;
  background-size: contain;
  background-position: center center;
}

.row-avatar{
  width: 60px;
  height: 60px;
  background-repeat: no-repeat;
  background-size: contain;
  background-position: center center;
  border: 1px solid #ccc;
}



.avatar-uploader-icon{
  font-size: 28px;
  width: 40px;
  height: 40px;
  align-items: center;
  justify-content: center;
}

.data-grid{
  margin-top: 6px;
}
.member-pi{
  margin-top: 6px;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>

<script setup>
import {nextTick, onMounted, reactive, ref, toRaw} from "vue";
import api from "@/util/api.js";
import {ElMessage, ElMessageBox} from "element-plus";

onMounted(async () =>{
   await search();
});

let members = ref();

let memberSearchReset = ref();


let memberPi = reactive({
  pageNo:1,
  pageSize:10,
  total:0
});

let memberSearchModel = ref({
  name:null,
  phone:null,
  regisdateRange :[]
});

async function search(pageNo=1,pageSize=10){
  let params = toRaw(memberSearchModel.value);
  if (params.regisdateRange){
    params.dateStart = params.regisdateRange[0];
    params.dateEnd = params.regisdateRange[1];
    delete params.regisdateRange;
  }

  let resp = await api({
    url:"/users",
    method:"get",
    //这里不是data
    params:{
      pageNo,
      pageSize,
      ...params
    }
  });

  // console.log(resp)
  members.value = resp.data.records;
  memberPi.pageNo = resp.data.current;
  memberPi.pageSize = resp.data.size;
  memberPi.total = resp.data.total;
}

//页面大小改变或者点击其他页时
function memberPiChange(pageNo,pageSize){
  search(pageNo,pageSize);
}

function reset(){
  memberSearchReset.value.resetFields();
  search();
}

const rules = {
  name:[{
    required:true,
    message:"请您填写姓名",
    trigger:"blur"
  }],
  phone:[{
    required:true,
    message:"宝宝你的手机号不要忘记填哦",
    trigger:"blur"
  },{
    min:11,
    max:11,
    message: "手机号你要写成11位哦",
    trigger: "blur"
  },{
    validator:validatorPhone
  }],
  integral:[{
    required:true,
    message:"请您填写积分",
    trigger:"blur"
  }],
  wechat:[{
    required:true,
    message:"请您填写微信号",
    trigger:"blur"
  }]
}

//校验手机号是否以一看开头
function validatorPhone(rule,value,cb) {
  if (value.startsWith("1")) {
    return cb();
  } else {
    return cb(new Error("手机号必须以1开头"));
  }
}

let memberDlgTitle = ref("新增客户");

let memberDlgShow = ref(false);

//初始化表单参数
let memberModel = ref({
  name:null,
  phone:null,
  isMember:"否",
  regisdate:null,
  integral:null,
  wechat:null,
  description:null,
  avatar : null
})


let mode = "add";

function add(){
  memberDlgShow.value = true;
  memberDlgTitle.value = "新增客户";
  mode = "add";
}

import {cloneDeep} from "lodash";
import * as row from "element-plus/es/locale/index";
import {Plus} from "@element-plus/icons-vue";
  function edit(row) {
    if (!row || !row.id) {
      ElMessage.error("请选择有效的客户数据");
      return;
    }

    memberDlgShow.value = true;
    memberDlgTitle.value = "修改客户信息";
    mode = "edit";

    //数据回显
    nextTick(() => {
      // 注意字段名称要与后端返回的数据一致
      memberModel.value = cloneDeep({
        id: row.id,
        name: row.name,
        phone: row.phone,
        avatar: row.avatar,
        isMember: row.isMember,
        regisdate: row.regisdate, // 注意这里字段名可能不同
        integral: row.integral,
        wechat: row.wechat,
        description: row.description
      });
    });
  };

function doSubmit(){
  if (mode === "add"){
    addSubmit();
  }else {
    editSubmit();
  }
}

async function addSubmit(){
  let params = toRaw(memberModel.value);
  let resp = await api ({
    url:"/users",
    method:"post",
    data:params
  });

  console.log(resp);
  if (resp.success){
    memberDlgShow.value = false;
    await search();
    ElMessage.success("添加客户成功");
  }else {
    ElMessage.error("添加客户失败");
  }
}

// 修改提交函数
async function editSubmit() {
  try {
    let params = toRaw(memberModel.value);
    let resp = await api({
      url: "/users", // 假设使用RESTful风格API
      method: "put",
      data: params
    });

    if (resp.success) {
      memberDlgShow.value = false;
      await search(memberPi.pageNo, memberPi.pageSize); // 保持当前分页
      ElMessage.success("修改客户成功");
    } else {
      ElMessage.error(resp.msg || "修改客户失败");
    }
  } catch (error) {
    ElMessage.error("修改客户时发生错误");
    console.error(error);
  }
}

//删除操作
function remove(row){
  ElMessageBox.confirm("是否确认删除要选中的行?","警告",{
    confirmButtonText:"确定",
    cancelButtonText:"取消",
    type:"warning"
  }).then(async () => {
    let resp = await api({
      url: "/users",
      method: "delete",
      data: [row.id]
    });
    if (resp.success) {
      ElMessage.success("删除成功");
      await search(memberPi.pageNo, memberPi.pageSize);
    } else {
      ElMessage.error(resp.msg || "删除失败");
    }
  }).catch(()=>{
  });
}

async function withPets(row){
  let resp =await api({
    url:"/users/withPet",
    method:"get",
    params:{
      id:row.id
    }
  });
  if (resp.data===null){
    remove(row);
  }else {
    ElMessage.error("您有宠物，暂时不提供删除操作");
  }
}

let memberDlgForm = ref();
function clearAll(){
  memberDlgForm.value.resetFields();
}

let memberDlgShow2 = ref(false);

let memberDlgTitle2 = ref("您的宠物🐕🐈‍⬛：");

let pets = ref();

async function YourPet(row){
  memberDlgShow2.value = true;
  let resp =await api({
    url:"/users/withPet",
    method:"get",
    params:{
      id:row.id
    }
  });
  console.log(resp);
  if (resp.success){
    pets.value = resp.data;
  }
}

////////////////////////////////////////////
//头像上传成功
//自定义上传函数
import baseUrl from "@/util/constant.js"

async function customUpload(options) {
  const formData = new FormData();
  formData.append('file', options.file);

  try {
    const resp = await api({
      url: '/users/avatar',
      method: 'post',
      data: formData,
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });

    if (resp.success) {
      options.onSuccess(resp);
      ElMessage.success("头像上传成功");
      let url = resp.data;
      memberModel.value.avatar = url;
      console.log(url);
    } else {
      options.onError(new Error(resp.msg));
      ElMessage.error(resp.msg || "头像上传失败");
    }
  } catch (error) {
    options.onError(error);
    ElMessage.error("上传过程中发生错误");
  }
}
</script>